/*
 * @Description: 文件内容描述
 * @Author: 李志杰
 * @Date: 2020-04-06 11:54:23
 * @LastEditTime: 2020-04-24 17:34:44
 * @LastEditors: huacong
 */
import _ from 'lodash';
import * as api from '@/services/ReportMgr';
import moment from 'moment';
import * as utils from '../utils/treeUtils';

const Model = {
  namespace: 'SupplyMarketingAnalysis',
  state: {
    all: [],
    overAllYears: [],
    expandedRowKeys: [],
    dataSource: [],
    currentChecked: ['supply', 'signing'],
    currentYear: moment().format('YYYY'),
    currentShowGroup: '期初存货/新供/综合',
    currentMonths: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '14'],
    currentLevel: 'project',
  },
  effects: {
    *requestData({ payload, callback }, { call, put, select }) {
      yield put({
        type: 'save',
        payload: { all: [], dataSource: [], expandedRowKeys: [] },
      });
      const currentLevel = yield select(state => state.SupplyMarketingAnalysis.currentLevel);
      const result = yield call(api.dmAnalyticalUsingGET, payload);
      if (result && result.code === 1) {
        const { timeList, detailList } = result.data;
        // 重洗数据
        const detailListAddValue = utils.getDetailListAddValue(detailList);
        // 默认显示到项目
        const dataLevel = utils.levelTree(detailListAddValue, currentLevel);
        // 历史年份当面加上（今年）标记
        const overAllYears = utils.getHistoryYearAddSign(timeList);
        // 展开的id
        const expandedRowKeys = utils.getExpandedRowKeys(dataLevel);
        // 构成树装数据
        const dataSource = utils.buildTree(dataLevel);
        yield put({
          type: 'save',
          payload: { all: detailListAddValue, overAllYears, dataSource, expandedRowKeys },
        });
      }
      if (callback) callback(result);
    },

    *changeCurrentYear({ payload, callback }, { call, put }) {
      yield put({
        type: 'save',
        payload: { currentYear: payload.currentYear },
      });
      if (callback) callback();
    },
  },
  reducers: {
    // 替换显示的内容
    changeCurrentVal(state, action) {
      const keys = action.payload;
      if (Object.keys(keys)[0] === 'currentLevel') {
        const levelTree = utils.levelTree(state.all, keys.currentLevel);
        const expandedRowKeys = utils.getExpandedRowKeys(levelTree);
        const dataSource = utils.buildTree(levelTree);
        return {
          ...state,
          ...keys,
          dataSource,
          expandedRowKeys,
        };
      }
      return {
        ...state,
        ...keys,
      };
    },
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};
export default Model;
